package com.mojo.jedis.controller;

import com.mojo.jedis.util.RedisUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * redis事务实践
 *
 * @author <a href="mailto:mojo_jj@163.com">Mojo</a>
 */
@RestController
@RequestMapping("redis")
public class TransactionController {
    private static final Logger logger = LoggerFactory.getLogger(TransactionController.class);
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private RedisUtil redisUtil;
    private Integer num = 0;

    @PostMapping("multi")
    public void multi() {
        redisTemplate.multi();
        ValueOperations<String, Object> operations = redisTemplate.opsForValue();
        operations.set("today", "friday");
        operations.set("tomorrow", "saturday");
        redisTemplate.exec();
    }

    /**
     * 使用自定义redis分布式锁
     */
    @GetMapping("/customLock")
    public void customLock() {
        // AtomicInteger num = new AtomicInteger(0);
        ExecutorService executors = Executors.newFixedThreadPool(10);
        List<CompletableFuture<?>> futures = new ArrayList<>();
        for (int i = 0; i < 100; i++) {
            //     CompletableFuture<?> submit = CompletableFuture.runAsync(() -> {
            //
            //         increase();
            //         Boolean isLocked = redisUtil.tryLock("lock", "customLock", 10);
            //         if (isLocked) {
            //             try {
            //                 num.incrementAndGet();
            //             } finally {
            //                 redisUtil.unlock("lock");
            //             }
            //         } else {
            //             logger.error(">>>>>>>>lock failed");
            //         }
            //     }, executors);
            //     futures.add(submit);
            // }
            // CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();
            // logger.info("num:{}", num.get());
            executors.submit(this::increase);

        }
        logger.info("====> num:{}", num);

    }

    private void increase() {
        num++;
    }
}